import { action, observable } from 'mobx'
import tokenAuthService from '../services/tokenAuth/tokenAuthService'
import sessionService from '../services/session/sessionService'
import LoginModel from '../models/login/loginModel'
import Taro from '@tarojs/taro';
import WxOpenLoginModel from '../models/login/wxOpenLoginModel';

class AuthenticationStore {
  @observable loginModel: LoginModel = new LoginModel();
  @observable isLogin: boolean = false;
  @observable accessToken: string
  @action
  public async login(model: LoginModel) {
    let result = await tokenAuthService.authenticate({
      userNameOrEmailAddress: model.userNameOrEmailAddress,
      password: model.password,
      rememberClient: model.rememberMe,
    })
    Taro.setStorageSync('access_token', result.accessToken)
  }

  @action
  public async wxOpenLogin(model: WxOpenLoginModel) {
    await tokenAuthService.wxOpenAuthenticate({
      code: model.code,
      state: model.state,
      encryptedData: model.encryptedData,
      iv: model.iv,
      rawData: model.rawData,
      signature: model.signature,
      returnUrl: '/'
    }).then(async (result) => {
      if (result.shouldBindingUser) {
        await tokenAuthService.wxBindingNoneUser({
          providerKey: result.providerKey,
          avatar: result.avatar,
          nickName: result.nickName,
          returnUrl: '/'
        }).then((user) => {
          if (user) {
            this.accessToken = user.accessToken
            Taro.setStorageSync('access_token', user.accessToken)
          }
        })
      } else {
        this.accessToken = result.accessToken
        Taro.setStorageSync('access_token', result.accessToken)
      }
    })
  }

  @action
  public async getLoginStatus() {
    await sessionService.getCurrentLoginInformations().then((res) => {
      if (res.user) {
        this.isLogin = true;
      }
      else {
        this.isLogin = false;
        Taro.removeStorageSync('access_token')
      }
    })

  }

  @action
  logout() {
    Taro.removeStorageSync('access_token');
  }

}
export default AuthenticationStore;
